<?php

class Maven_ManageCatalogSpr_Model_SprStockUpdate extends Varien_Object
{
	public $con;
	public $zipArray = array();
	public $fileArray = array();
	public $logMsg = array();
	public $manageCatalogId;
	public $store;
	protected $_stores;
	protected $_storesIdCode;
	public $websiteIds;
	
	const BULK_UPDATE_STOCK        = true;

	public function __construct()
	{
		$this->con = Mage::getSingleton('core/resource')->getConnection('core_write');
		$this->store = $this->getStoreByCode('admin');
		$this->websiteIds = array(1);
	}

	/**
	 *  Init stores
	 *
	 *  @param    none
	 *  @return      void
	 */
	protected function _initStores ()
	{
		if (is_null($this->_stores)) {
			$this->_stores = Mage::app()->getStores(true, true);
			foreach ($this->_stores as $code => $store) {
				$this->_storesIdCode[$store->getId()] = $code;
			}
		}
	}

	/**
	 * Retrieve store object by code
	 *
	 * @param string $store
	 * @return Mage_Core_Model_Store
	 */
	public function getStoreByCode($store)
	{
		$this->_initStores();
		if (isset($this->_stores[$store])) {
			return $this->_stores[$store];
		}
		return false;
	}
	public function getConfigVal($field)
	{
		return Mage::getStoreConfig('managecatalogspr/spr_stock_update/'.$field);
	}
	public function writeLog($msg,$forceWrite=true)
	{
		$this->logMsg[] = $msg;
		//if($forceWrite)
		//{
			$str = implode("\n", $this->logMsg);
			Mage::log($str, 7, $this->getConfigVal('log_file'));
			$this->logMsg = array();
		//   }
	}
	public function setManageCatalogId($mcid)
	{
		$this->manageCatalogId = $mcid;
	}
	public function getManageCatalogId()
	{
		return $this->manageCatalogId;
	}
	public function cleanLog($flag=true)
	{
	    if($flag) {
			$log_file = Mage::getBaseDir('var').DS.'log'.DS.$this->getConfigVal('log_file');
			if(file_exists($log_file)) {
				unlink($log_file);
			}
		}
	}
	public function getLog()
	{
		$log_file = Mage::getBaseDir('var').DS.'log'.DS.$this->getConfigVal('log_file');
		$buffer='';
		if(file_exists($log_file)) {
			$handle = fopen($log_file, "r");
			if ($handle) {
				while (!feof($handle)) {
					$buffer .= "<BR/>".fgets($handle, 4096);
				}
				fclose($handle);
			}
		}
		return $buffer;
	}

	public function updateStock($data)
	{
		if ($data['product_id']!='') {
			try {
				//Save Product Stoct Item.
				$stockItem = Mage::getModel('cataloginventory/stock_item');
				$stockItem->loadByProduct($data['product_id']);
				$sid = $stockItem->getId();
				if (!$sid) {
					$stockItem->setProductId($data['product_id'])->setStockId(1);
					$stockItem->setStoreId($this->store->getId());
					//$stockItem->setProduct($product);
				}
				$stockItem->setData('qty', $data['qty']);
				$stockItem->setData('manage_stock', 1);
				$stockItem->setData('is_in_stock',$data['is_in_stock'] );
				$stockItem->save();
				
				$this->writeLog("Sku updated: ".$sku,0);
				//unset($product);
				unset($stockItem);
				return true;
			} catch (Exception $e) {
				$this->writeLog("Sku Stock update Fail: ".$sku. " --> Due to problem : ".$e->getMessage(),0);
				return false;
			}
		}
		else {
			$this->writeLog("Sku not found: ".$sku,0);
			return false;
		}

	}

	public function setFile($file_name)
	{
		$this->fileArray[] = $file_name;
	}
	
	/**
	 * Unzip the source_file in the destination dir
	 * @Todo work only for the windows OS
	 * @param   string      The path to the ZIP-file.
	 * @param   string      The path where the zipfile should be unpacked, if false the directory of the zip-file is used
	 * @param   boolean     Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
	 * @param   boolean     Overwrite existing files (true) or not (false)
	 *
	 * @return  boolean     Succesful or not
	 */
	public function unzip1($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
	{
		if(function_exists("zip_open"))
		{
			if(!is_resource(zip_open($src_file)))
			{
				$src_file=dirname($_SERVER['SCRIPT_FILENAME'])."/".$src_file;
			}

			if (is_resource($zip = zip_open($src_file)))
			{
				$splitter = ($create_zip_name_dir === true) ? "." : "/";
				if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
					
				// Create the directories to the destination dir if they don't already exist
				$this->create_dirs($dest_dir);

				// For every file in the zip-packet
				while ($zip_entry = zip_read($zip))
				{
					// Now we're going to create the directories in the destination directories

					// If the file is not in the root dir
					$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
					if ($pos_last_slash !== false)
					{
						// Create the directory where the zip-entry should be saved (with a "/" at the end)
						$this->create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
					}

					// Open the entry
					if (zip_entry_open($zip,$zip_entry,"r"))
					{
							
						// The name of the file to save on the disk
						$file_name = $dest_dir.zip_entry_name($zip_entry);
						$this->setFile($file_name);
						
						// Check if the files should be overwritten or not
						if ($overwrite === true || $overwrite === false && !is_file($file_name))
						{
							// Get the content of the zip entry
							$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

							if(!is_dir($file_name))
							file_put_contents($file_name, $fstream );
							// Set the rights
							if(file_exists($file_name))
							{
								chmod($file_name, 0777);
								//echo "<br />\n<span style=\"color:#1da319;\">file saved: </span>".$file_name."<br />";
							}
							else
							{
								$this->writeLog("<br />\n<span style=\"color:red;\">file not found: </span>".$file_name."<br />");
								die( "<br />\n<span style=\"color:red;\">file not found: </span>".$file_name."<br />");
							}
						}
							
						// Close the entry
						zip_entry_close($zip_entry);
					}
				}
				// Close the zip-file
				zip_close($zip);
			}
			else
			{
				$this->writeLog("No Zip Archive Found");
				die("No Zip Archive Found.");
				return false;
			}

			return true;
		}
		else
		{
			if(version_compare(phpversion(), "5.2.0", "<"))
			$infoVersion="(use PHP 5.2.0 or later)";
			$this->writeLog("<br />\nYou need to install/enable the php_zip.dll extension $infoVersion");
			die("<br />\nYou need to install/enable the php_zip.dll extension $infoVersion");
		}
	}
	/**
	 * @Todo work only for the windows OS
	 * @param unknown_type $path
	 * @return unknown_type
	 */
	public function create_dirs($path)
	{
		if (!is_dir($path))
		{
			$directory_path = "";
			$directories = explode("/",$path);
			array_pop($directories);

			foreach($directories as $directory)
			{
				$directory_path .= $directory."/";
				if (!is_dir($directory_path))
				{
					mkdir($directory_path);
					chmod($directory_path, 0777);
				}
			}
		}
	}
	public function unzip($src_file)
	{
	    
		//echo ET_IMPORT_PATH.$src_file;
		$file_name = substr($src_file,0,-5).".ezoh";
		exec('cd '.Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::SPR_STOCK_FOLDER),$echoed);
		exec('unzip -o  ' . $src_file. ' -d '.Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::SPR_STOCK_FOLDER),$echoed);
		$this->fileArray[] = $file_name;
	}


	public function processFile($file)
	{
		$impObj = Mage::getModel('managecatalogspr/Import');
		$tempStock = Mage::getResourceModel('managecatalogspr/temp_sprstock');
		try {
			$tempStock->loadDataInfile($file);
			
			$this->writeLog($file." Processed Successfully ! ");
			$impObj->saveSprStockEntry(
				array(	'total'=> $tempStock->getCountData(),
						'success'=> $tempStock->getSuccessCount(),
						'fail'=> $tempStock->getFailCount(),
						'status'=> 1, 
						'content'=>implode("\n",$this->logMsg)),$this->getManageCatalogId());
			return true;
		} catch (Exception $e) {
			$this->writeLog($file." Processed Failure ! ". $e->getMessage());
			$impObj->saveSprStockEntry(
				array(	'total'=> $tempStock->getCountData(),
						'success'=> $tempStock->getSuccessCount(),
						'fail'=> $tempStock->getFailCount(),
						'status'=> 3, 
					  	'content'=>implode("\n",$this->logMsg)),$this->getManageCatalogId());
			return false;
		}
		
	}

	public function getFiles()
	{
		foreach($this->fileArray as $f) {
			$ar = explode("/",$f);
			$ar_new[] = end($ar);
		}
		return implode(",",$ar_new);
	}
	public function process()
	{
	   /** For testing **/
		//$this->fileArray= array();
		//$this->fileArray[]=Maven_ManageCatalog_Model_Setting::getImportPath(Maven_ManageCatalog_Model_Setting::STOCK_FOLDER).'TOTAL2.TXT';
        /** testing end **/
        
		foreach($this->fileArray as $file) {
			$this->processFile($file);
		}
		
		$impObj = Mage::getModel('managecatalogspr/Import');
		$countArray =array('success'=>0,'fail'=>0,'total'=>0,'counter'=>0,'status'=>0);
		
		if(self::BULK_UPDATE_STOCK) {
			$tempStock = Mage::getResourceModel('managecatalogspr/temp_sprstock');
        	foreach($this->fileArray as $file) {
	          	$tempStock->updateProductStock($file);
                $countArray['total'] = $tempStock->getCountData();
    			$countArray['success'] = $tempStock->getSuccessCount();
    			$countArray['fail'] = $countArray['total'] - $countArray['success'];
    			$impObj->saveSprStockEntry($countArray,$this->getManageCatalogId());
            }    
			
		}else {
			$cond = " WHERE ts.product_id IS NOT NULL AND status=0 ";

			$resTotal = $this->con->query("SELECT count(*) as total FROM temp_stock_sp as ts ".$cond)->fetchAll();

			if(isset($resTotal[0]['total'])) {
				$countArray['total'] = $resTotal[0]['total'];
				while ($countArray['total'] > $countArray['counter']) {
					$res = $this->con->query(
						"SELECT product_id, qty, is_in_stock  FROM temp_stock_sp as ts ".$cond. " LIMIT 0,100")->fetchAll();
					foreach ($res as $data) {
						if($this->updateStock($data)) {
							$countArray['success']++;
							$this->con->query("UPDATE temp_stock_sp SET status=1 WHERE product_id = ".$data['product_id']);
						}else {  //fail track
							$countArray['fail']++;
						}
						$countArray['counter']++;
					}
					if(($countArray['counter']%1000)==0) {
						$impObj->saveSprStockEntry($countArray,$this->getManageCatalogId());
						$this->writeLog("=>Processed:".$counter);
					}
				}
			}
		}
	}
	public function list_all_files($conn_id, $path){
		
		ftp_pasv($conn_id,true);
		$buff = ftp_nlist($conn_id, $path);
		$final =  preg_grep('/.zip$/i',$buff);
       	$i =0;
		$zipArray = array();
		foreach ($final as $val) {
			if(strstr($val,$this->getConfigVal('file_suffix'))) {
				$ar = explode("/",$val);
				$zipArray[] = end($ar);
			}
		}
       	return $zipArray;
	}

	public function downloadFiles()
	{  
	   
	    $conn_id = ftp_connect($this->getConfigVal('stock_ftp_url'));
        // login with username and password
		$login_result = ftp_login($conn_id, $this->getConfigVal('user'), $this->getConfigVal('password'));
        $Zips = $this->list_all_files($conn_id, $this->getConfigVal('stock_ftp_path'));
       	foreach($Zips as $Zip) {
       		if (ftp_get($conn_id, Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::SPR_STOCK_FOLDER).$Zip,
			$this->getConfigVal('stock_ftp_path')."/".$Zip, FTP_BINARY)) {
				if(PHP_OS == 'WINNT'){
		          $this->unzip1(Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::SPR_STOCK_FOLDER).$Zip); 
			    }else{
                  $this->unzip(Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::SPR_STOCK_FOLDER).$Zip);
			    }
                
				$this->writeLog($Zip ." Downloaded Successfully ! ");
			}else {
				$this->writeLog($Zip ." Downloading Problem ! ");
			}
		}
       	ftp_close($conn_id);
	}
	public function sendStatus($mc_id)
	{
		//system('zip -r '.Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::SPR_STOCK_FOLDER).'stock_log.zip '.Mage::getBaseDir('var').DS.'log'.DS.$this->getConfigVal('log_file'));
		$link = Maven_ManageCatalogSpr_Model_Setting::getImportUrl(Maven_ManageCatalogSpr_Model_Setting::SPR_STOCK_FOLDER).'stock_log.zip';
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

		// Additional headers
		$headers .= 'To: SPR Stock Update '.Mage::getStoreConfig('managecatalogspr/general/email'). "\r\n";
		//$headers .= 'From: system <system@flatrox.com>' . "\r\n";
		$headers .= 'Cc: '.Mage::getStoreConfig('managecatalogspr/general/ccemail') . "\r\n";

        if($mc_id){
         $mc = Mage::getModel('managecatalogspr/managecatalog')->load($mc_id);
         $success=$mc->getSuccess();
         $fail=$mc->getFail();
         $total=$mc->getTotal();
        
		 $startTime=Mage::helper('managecatalogspr')->getFormattedDateTime($mc->getCreatedTime());
		 $FinishTime=Mage::helper('managecatalogspr')->getFormattedDateTime($mc->getUpdateTime());
		 $message ="SPR Stock udpate process completed successfully!". "<br>";
		 $message .= "Start time:".$startTime."<br/>";
		 $message .= "End time  :".$FinishTime."<br/>";  
         $message .= "Success : ".$success. "<br/>";
         $message .= "Fail    : ".$fail. "<br/>";
         $message .= "Total   : ".$total. "<br/>";
    	 
         }else{
            $message = "Run Time Error". "<br>";
         }
		@mail(Mage::getStoreConfig('managecatalogspr/general/email'), "Stock Update Log", nl2br($message), $headers);
	}
}

